<?php
/**
 * FastApp.
 * 9/19/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Game\Api\Service;

use App\Fastapp\Api\Service\BaseService;
use App\Game\Model\GameCategory;
use App\Game\Model\GameFavorite;

class FavoriteService extends BaseService
{
    public function list(array $param): array
    {
        $map['user_id'] = get_uid();
        if (is_numeric($param['status'] ?? '')) $map['status'] = $param['status'];
        if (is_numeric($param['view'] ?? '')) $map['view'] = $param['view'];
        $query = GameFavorite::query()
            ->with(['game:id,name,icon,cover,platform,provider,code', 'tag'])
            ->where($map);
        $paginate = $query->orderByDesc('last_at')->simplePaginate();
        $list = [];
        foreach ($paginate->items() as $item) {
            if (!$item->game) continue;
            $game = $item->game;
            $game->name = fastapp_lang_text($game->name);
            $game->status = $item->status;
            $game->last_at = $item->last_at;
            $tags = [];
            foreach ($item->tag as $tag) {
                if (!$tag->tag) continue;
                $tags[] = fastapp_lang_text($tag->tag->name);
            }
            $game->tag = $tags;
            $list[] = $game;
        }
        return ['list' => $list];
    }

    public function add(int $game_id, int $uid = 0, ?int $view = 0, ?int $status = 0): bool|int
    {
        $uid = $uid ?: get_uid();
        $md = GameFavorite::query()->firstOrCreate(['user_id' => $uid, 'game_id' => $game_id]);
        $up['last_at'] = date('Y-m-d H:i:s');
        if (is_int($status)) $up['status'] = $status;
        if (is_int($view)) $up['view'] = $view;
        return $md->update($up);
    }

    public function last(): array
    {
        $map['user_id'] = get_uid();
        $gids = GameFavorite::query()->where($map)->pluck('game_id')->toArray();
        $res = GameCategory::query()->with(['category:id,name'])
            ->selectRaw('category_id,count(*) as num')
            ->whereIn('game_id', $gids)->groupBy('category_id')->get()->map(function ($item) {
                return ['num' => $item->num, 'name' => fastapp_lang_text($item->category->name)];
            })->pluck('name', 'num')->toArray();
        krsort($res);
        $list = GameFavorite::query()->with(['game:id,cover,platform,provider,code'])->where($map)
            ->orderByDesc('last_at')
            ->limit(4)->get()->map(function ($item) {
                return $item->game?->cover;
            });
        $num = array_keys($res)[0] ?? 0;
        return [
            'total_num' => count($gids),
            'list' => $list,
            'more_category' => [
                'num' => $num,
                'name' => $res[$num] ?? '',
            ]
        ];
    }
}